import path from 'path'
import { updateHandle } from './updater'
import connectDB from './sqlite'
import { app, BrowserWindow, protocol, Menu, globalShortcut, clipboard } from 'electron'

function composeURL (url: string) {
  if (process.argv.length < 2) return url
  const length = 'vite:///'.length
  const route = process.argv.pop()
  return url.concat(route?.slice(length) ?? '')
}

app.removeAsDefaultProtocolClient('vite')
protocol.registerSchemesAsPrivileged([{ scheme: 'vite' }])
let argvs: string[] = []
if (process.argv.length > 1) {
  argvs = [path.resolve(process.argv[1])]
}
// If we are running a non-packaged version of the app && on windows
app.setAsDefaultProtocolClient('vite', process.execPath, argvs)

//定义全局变量获取 窗口实例
let win: BrowserWindow | null
let currentWin: BrowserWindow | null

function loadSelection () {
  return currentWin?.webContents.executeJavaScript(`
  (function () {
    const data = window.getSelection()
    return Promise.resolve(data?.toString())
  })()`, true)
}

const contextMenu = Menu.buildFromTemplate([
  {
    label: '返 回', id: 'back', accelerator: "Alt+Left", click () {
      win?.webContents.goBack()
    }
  },
  {
    label: '控制台', id: 'tools', click () {
      currentWin?.webContents.openDevTools()
    }
  },
  { label: '刷 新', role: 'reload', id: 'reload', accelerator: "Ctrl+F5" },
  { label: '复 制', role: 'copy', id: 'copy', accelerator: "Ctrl+C", },
  { label: '粘 贴', role: 'paste', id: 'paste', accelerator: "Ctrl+V", },
  {
    label: '查找', id: 'find', accelerator: "Ctrl+F", click () {
      loadSelection()?.then((result) => {
        console.log(result)
        // setInterval(() => {
        //   currentWin?.webContents.findInPage(result, {
        //     findNext: true
        //   })
        // }, 1200)
      })
    }
  },
])

function setMenuVisible (menu: Menu, shows: string[]) {
  const data = ['reload', 'tools'].concat(shows)
  for (const item of menu.items) {
    item.visible = data.includes(item.id)
  }

  return menu
}


const createWindow = () => {
  process.env['ELECTRON_DISABLE_SECURITY_WARNINGS'] = 'true';

  win = new BrowserWindow({
    autoHideMenuBar: true,
    show: false,
    width: 1200,
    // closable: false,
    webPreferences: {
      devTools: true,
      contextIsolation: false,
      webSecurity: false,
      nodeIntegration: true,
      preload: path.join(__dirname, 'preload'),
    }
  })

  if (process.env.VITE_DEV_SERVER_URL) {
    if (process.env.IS_TEST ?? true) {
      win.webContents.openDevTools()
    }
    // Load the url of the dev server if in development mode
    // win.loadURL('https://www.baidu.com')
    win.loadURL(composeURL(process.env.VITE_DEV_SERVER_URL))
  } else {
    win.webContents.openDevTools()
    // Load the index.html when not in development
    const dist = '../dist/index.html'
    // win.loadFile(composeURL(dist))
    // win.loadURL(composeURL('https://www.baidu.com'))
    win.loadURL(composeURL(`file://${path.join(__dirname, dist)}`))
  }

  win.on('ready-to-show', () => {
    if (win !== null) {
      const version = app.getVersion()
      updateHandle(win)
      win.show()
      win.webContents.send('logVersion', version)
    }
  })

  win.webContents.setWindowOpenHandler((details) => {
    if (details.url) {
      return {
        action: 'allow',
        overrideBrowserWindowOptions: {
          webPreferences: {
            webSecurity: false,
            sandbox: false,
            preload: path.join(__dirname, 'preload')
          }
        }
      }
    }
    return { action: 'deny' }
  })

  connectDB().then(db => {
    db.serialize(() => {
      console.log('log serialize successful')
    })
  }).catch(err => {
    win?.webContents?.send('serializefailed')
  })
}

app.whenReady().then(() => {
  createWindow()
  globalShortcut.register('CmdOrCtrl+F5', () => {
    currentWin?.reload()
  })
})

// macOS
app.on('open-url', (_, url) => {
  const win = new BrowserWindow({
    autoHideMenuBar: true,
    show: false,
    width: 1200,
    webPreferences: {
      devTools: true,
      contextIsolation: false,
      webSecurity: false,
      nodeIntegration: true,
      preload: path.join(__dirname, 'preload'),
    }
  })

  win.loadURL('https://www.npmjs.com')
})

app.on('activate', () => {
  const wins = BrowserWindow.getAllWindows()
  if (wins.length === 0) createWindow()
})

const inputs = ['plainText', 'password']
app.on('browser-window-created', (_, win) => {
  currentWin = win
  win.setMenu(null)

  win.webContents.on('context-menu', (e, params) => {
    const shows: string[] = []
    if (win.webContents.canGoBack()) shows.push('back')
    if (params.selectionText) shows.push('copy', 'find')
    const paste = inputs.includes(params.inputFieldType)
    if (paste && clipboard.readText()) shows.push('paste')
    if (contextMenu) setMenuVisible(contextMenu, shows).popup()
  })

  win.webContents.on('found-in-page', (e, result) => {
    if (result.finalUpdate) {
      // win.webContents.stopFindInPage('keepSelection')
    }
  })
})

app.on('window-all-closed', () => {
  globalShortcut.unregisterAll()
  if (process.platform !== 'darwin') {
    app.quit()
  }
})